<?php
class Simpple_Logger {
	const LOGGER_INFO = 'info';
	const LOGGER_WARNING = 'warning';
	const LOGGER_ERROR = 'error';
	
	const MAX_BUFFER_LINE = 10;
	
	private $buffer = array();	
	private $fh = null;
	
	public function __construct($path) {
		$this->fh = fopen($path, 'a+');
		
	}
	
	private static $loggerDir;
	/**
	 * 默认日志器
	 *
	 * @var Logger
	 */
	private static $loggers;
	/**
	 * 设置日志目录
	 *
	 * @param string $dir
	 */
	public static function setLoggerDir($dir) {
		self::$loggerDir = $dir;
	}
	/**
	 * 获取日志读写器
	 *
	 * @param string $prefix
	 * @return Simpple_Logger
	 */
	public static function getLogger($prefix='www') {
		if (!preg_match("{^[a-zA-Z]{1,20}}", $prefix)) {
			die('illegal prefix');
		}
		if (isset(self::$loggers[$prefix])) {
			return self::$loggers[$prefix];
		}
		if (!self::$loggerDir) {
			die('the logger dir is undefined');
		}
		$fileName = $prefix.'-'.date('Y-m').'.log';
		return (self::$loggers[$prefix] = new Simpple_Logger(self::$loggerDir.'/'. $fileName) );
	}
	
	/**
	 * 记录信息
	 *
	 * @param string $msg
	 */
	public function info($msg) {
		$this->log(self::LOGGER_INFO, $msg);
	}
	
	/**
	 * 警告信息
	 *
	 * @param string $msg
	 */
	public function warning($msg) {
		$this->log(self::LOGGER_WARNING, $msg);
	}
	
	/**
	 * 错误信息
	 *
	 * @param string $msg
	 */
	public function error($msg) {
		$this->log(self::LOGGER_ERROR, $msg);
	}
	
	/**
	 * 写日志
	 *
	 * @param string $type
	 * @param string $msg
	 */
	public function log($type, $msg) {
		if (!in_array($type, array(
			self::LOGGER_WARNING,
			self::LOGGER_INFO,
			self::LOGGER_ERROR,
		))) {
			die('wrong log type');
		}
		$this->write($this->formatMsg($type, $msg));
	}
	
	private function formatMsg($type, $msg) {
		if (is_array($msg)) {
			$msg = json_encode($msg);
		}
		return date('r')." [{$type}]:{$msg}\n";
	}
	
	/**
	 * 写日志
	 *
	 * @param string $str
	 */
	private function write($str) {
		array_push($this->buffer, $str);
		if (count($this->buffer) >= self::MAX_BUFFER_LINE) {
			$this->_realWrite();
		}
	}
	
	/**
	 * 实际写入数据
	 *
	 */
	private function _realWrite() {
		fwrite($this->fh, implode('', $this->buffer));
		$this->buffer = array();
	}
	
	/**
	 * 写入剩余的缓存，销毁文件句柄
	 *
	 */
	public function __destruct() {
		if (!empty($this->buffer)) {
			$this->_realWrite();
		}
		fclose($this->fh);
	}
	
	/**
	 * 关闭日志
	 */
	public static function close() {
		if (!self::$loggers) return;
		foreach(self::$loggers as $logger) {
			$logger->__destruct();
		}
	}
}